Skip to main content

Delete Old Files to Max Folder Size

Description

The delete_old_files_max_folder_size function manages the size of a folder by deleting the oldest files until the total size of the folder is below a specified maximum size. This is useful for cleaning up directories that need to maintain a certain size limit.

Function Signature:

def delete_old_files_max_folder_size(folder_path: str, max_size_mb: int):

Parameters

  • folder_path (str): The path to the folder where files will be deleted.
  • max_size_mb (int): The maximum allowed size for the folder in megabytes. Files will be deleted until the total size is below this threshold.

Returns

  • None: The function does not return any value. It performs actions directly on the file system.

Example Usage

delete_old_files_max_folder_size('/path/to/folder', 100)

Notes

  • The function works by calculating the total size of the files in the specified folder.
  • If the total size exceeds the specified limit (max_size_mb), the oldest files will be deleted first until the folder size is within the limit.
  • The function uses the os.path.getctime to determine the creation time of the files for sorting.
  • It assumes that the folder contains only files (no directories).

Error Handling

  • The function does not explicitly handle errors, but if an exception occurs (e.g., due to file permissions), it will stop and may raise an error.